/*********************
* Author:Dzlua
* QQ:505544956
* time:2016/08/15
*/
#include "Dialog.h"

#define DIALOG_WND_WIDTH 300
#define DIALOG_WND_HEIGHT 150

Dialog::Dialog() : m_wnd(0)
{}

Dialog::~Dialog()
{
    this->Close();
}

void Dialog::Show(IWindow* parent, const char* text, const Point pt, void* data1, void* data2)
{
    if (!m_wnd){
        m_wnd = IEnginePtr->GetWindowInterface();
        String name;
        name.Format("dialog-%d", this);
        bool bOK = false;
        bOK = m_wnd->Create(name, "dialog", pt.x, pt.y, DIALOG_WND_WIDTH, DIALOG_WND_HEIGHT, WINDOW_BORDERLESS);
        if (!bOK){
            m_wnd->Release();
            Log("[Dialog] : create dialog error.");
        }

        if (!m_wnd->LoadLayout("wnd/dialog.xml")){
            Log("[Dialog] : load dialog window layout error.");
            return;
        }
        
        Button* button = Button::ToButton(m_wnd->FindControl("dclose"));
        if (button){
            button->evt.click.connect(this, &Dialog::onButtonCloseClick);
        }
        button = Button::ToButton(m_wnd->FindControl("dyes"));
        if (button){
            button->evt.click.connect(this, &Dialog::onButtonYesClick);
        }
        button = Button::ToButton(m_wnd->FindControl("dcancel"));
        if (button){
            button->evt.click.connect(this, &Dialog::onButtonCancelClick);
        }
    }

    Control* ctrl = m_wnd->FindControl("dtext");
    if (ctrl){
        Label::ToLabel(ctrl)->SetText(text);
    }
    m_data1 = data1;
    m_data2 = data2;

    m_wnd->SetParent(parent);

    m_wnd->ShowWindow();
}

void Dialog::Show(IWindow* parent, const char* text, void* data1, void* data2)
{
    Point pt(WINDOWPOS_CENTERED, WINDOWPOS_CENTERED);
    this->Show(parent, text, pt, data1, data2);
}

void Dialog::Show(IWindow* parent, const char* text, const Rect rc, void* data1, void* data2)
{
    Point pt( rc.x + (rc.w - DIALOG_WND_WIDTH)/2, rc.y + (rc.h - DIALOG_WND_HEIGHT)/2);
    this->Show(parent, text, pt, data1, data2);
}

void Dialog::Close()
{
    if (m_wnd){
        m_wnd->Close();
        m_wnd = 0;
    }
    m_data1 = 0;
    m_data2 = 0;
}

//--------------//
void Dialog::onButtonCloseClick(Button* btn)
{
    this->evt.close.emit(this, m_data1, m_data2);
    this->Close();
}

void Dialog::onButtonYesClick(Button* btn)
{
    this->evt.yes.emit(this, m_data1, m_data2);
}

void Dialog::onButtonCancelClick(Button* btn)
{
    this->evt.cancel.emit(this, m_data1, m_data2);
}
